<?php

namespace App\Http\Controllers\Web;

use App\Driver;
use App\Line;
use App\Utils\CommonCRUD;
use DB;
use Illuminate\Http\Request;

class DriverController extends Controller
{
    use CommonCRUD;

    protected $_viewGroup = 'web';
    protected $_view = 'driver';
    // protected $_orderField = 'no';
    // protected $_order = 'asc';

    protected $_model;
    protected $_where=[];

    public function __construct(Driver $model,Request $request)
    {

        $this->_model = $model;
        $this->_where = function($qy) use($request) {
            if($request->input('key')!='') {
                $qy->where('name','like',$request->input('key').'%');
                $qy->orWhere('phone','like',$request->input('key').'%');
            }

        };
    }

    protected function _before_add(Request $request) {
        return [
            'line_list'=> Line::get()
        ];
    }

    public function _before_postAdd(Request $request) {

        //验证
        $this->validate($request, [
            'name' => 'required',
            'phone' => 'required',
            'car_no' => 'required',
            'car_type' => 'required',
            'num' => 'required|numeric|min:1',
            'num' => 'required|numeric|min:0',
            'line_id' => 'required',
        ]);
        return [
            'free'=>$request->input('num')
        ];
    }

    protected function _before_edit(Request $request) {
        return [
            'line_list'=> Line::get()
        ];
    }

    public function _before_postEdit(Request $request) {

        //验证
        $this->validate($request, [
            'name' => 'required',
            'phone' => 'required',
            'car_no' => 'required',
            'car_type' => 'required',
            'num' => 'required|numeric|min:1',
            'num' => 'required|numeric|min:0',
            'line_id' => 'required',
        ]);

    }

    public function end_trip(Request $request) {
        $driver = Driver::find($request->input('id'));

        if(!$driver) {
            return back()->withErrors('司机信息不存在！');
        }

        try {

            DB::beginTransaction();

            DB::table('orders')
                ->where('status', 2)
                ->where('driver_id', $driver->id)
                ->update([
                    'status' => 3
                ]);

            $driver->free = $driver->num;
            $driver->return_trip = ($driver->return_trip == 1)?0:1;
            $driver->save();

            DB::commit();

            return redirect()->route('admin.driver')->with('msg','操作成功！');

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('结束行程失败！'.$e->getMessage());
            back()->withErrors('结束行程失败！');
        }

    }


}
